package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"store/cathe"
	"store/models"
)

type StoreController struct {
	beego.Controller
}

func (c *StoreController) Add() {

	storeId := c.GetString("storeId")
	types := c.GetString("types")
	name := c.GetString("name")
	num, _ := c.GetInt("num")
	price, _ := c.GetFloat("price")
	carname := c.GetString("carname")
	store := models.Store{
		StoreId: storeId,
		Types:   types,
		Name:    name,
		Num:     num,
		Price:   price,
		Carname: carname,
	}
	err := store.Create()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *StoreController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var store []*models.Store
	catheData := cathe.Rdb.Get(cathe.Ctx, "store_list").Val()
	if catheData == "" {
		var store models.Store
		data, _ := store.List()
		jsonData, _ := json.Marshal(data)
		cathe.Rdb.Set(cathe.Ctx, "store_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(catheData), &store)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "获取成功",
		"data": &store,
	}
	c.ServeJSON()
	return
}

type Response struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Size    int         `json:"size"`
	Count   int64       `json:"count"`
	Sumpage int         `json:"sumpage"`
}

func (c *StoreController) Pagelist() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var strore []*models.Store
	page, _ := c.GetInt("page")
	size, _ := c.GetInt("size")
	var count int64
	models.DB.Model(&models.Store{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	err := models.DB.Offset(offset).Limit(size).Find(&strore).Error
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "获取失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Response{
			Code:    200,
			Msg:     "获取成功",
			Data:    &strore,
			Page:    page,
			Size:    size,
			Count:   count,
			Sumpage: sumpage,
		}
		c.ServeJSON()
		return
	}
}
